<template>
  <div class="users">
    <BreadCrumb :item="['用户管理', '用户列表']"></BreadCrumb>
    <!-- 主体 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-input
          placeholder="请输入内容"
          v-model="searchContent"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="searchTable"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="showDialog('add')"
          >添加用户</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        :pagesize="pagesize"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="48px"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="address" label="状态">
          <template #default="{ row }">
            <el-switch v-model="row.mg_state" @change="changeState(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260px" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showDialog('edit', row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-star-off"
              size="mini"
              @click="showDialog('allot', row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[2, 1, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹出层 -->
    <el-dialog
      :title="typeTitle"
      :visible.sync="dialogFormVisible"
      @close="handleClose"
    >
      <!-- 分配角色 -->
      <div v-if="type === 'allot'">
        <p>当前用户:{{ form.username }}</p>
        <p class="allot-roles">当前用户:{{ form.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="rolesValue" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 添加表单 -->
      <el-form v-else ref="form" :model="form" :rules="rules">
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input
            v-model="form.username"
            autocomplete="off"
            :disabled="type === 'edit'"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="type === 'add'"
          label="密码"
          label-width="80px"
          prop="password"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="80px" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserMsg">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  addUser,
  changeRoles,
  changeUserState,
  delUser,
  distributeUser,
  editUserDetail,
  getUserDetail,
} from '@/api/user'
import { Message } from 'element-ui'
const mapTitle = {
  add: '添加用户',
  edit: '编辑用户',
  allot: '分配角色',
}
export default {
  name: 'Users',

  data() {
    return {
      tableData: [],
      rolesList: [],
      pagenum: 1,
      pagesize: 2,
      total: 0,
      dialogFormVisible: false,
      searchContent: null,
      type: 'add',
      rolesValue: '',
      form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度需要在6到15之间', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern:
              /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: '请输入合法的邮箱',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入合法的手机号',
            trigger: 'blur',
          },
        ],
        rolesValue: [{ required: true, message: '请至少选择一项' }],
      },
    }
  },
  methods: {
    // 初始化数据
    async initUserList() {
      const res = await getUserList({
        query: this.searchContent,
        pagenum: this.pagenum,
        pagesize: this.pagesize,
      })
      // console.log(res)
      this.tableData = res.data.users
      this.total = res.data.total
      this.mg_state = res.data.mg_state
    },
    // 每页显示条数变化
    handleSizeChange(val) {
      this.pagesize = val
      this.initUserList()
    },
    // 当前页数发生变化
    handleCurrentChange(val) {
      this.pagenum = val
      this.initUserList()
    },
    // 状态变化
    async changeState(row) {
      // row.mg_state = !row.mg_state
      const res = await changeUserState(row.id, row.mg_state)
      // console.log(res)
      row.mg_state = res.data.mg_state ? true : false
      this.initUserList()
    },
    // 添加用户,编辑用户和修改角色
    async addUserMsg() {
      if (this.type === 'add') {
        await this.$refs.form.validate()
        await addUser(this.form)
        Message('添加成功')
      }
      if (this.type === 'edit') {
        await this.$refs.form.validate()
        const { username, mobile, email, id } = this.form
        await editUserDetail(id, {
          username,
          mobile,
          email,
        })
        Message('修改成功')
      }
      if (this.type === 'allot') {
        // console.log(this.rolesValue)
        await changeRoles(this.form.id, {
          rid: this.rolesValue,
        })
      }
      this.dialogFormVisible = false
      this.initUserList()
    },
    // 操作弹层
    async showDialog(type, row) {
      this.type = type
      if (type === 'edit') {
        const res = await getUserDetail(row.id)
        // console.log(res)
        this.form = { ...res.data }
      }
      if (type === 'allot') {
        this.form.username = row.username
        this.form.role_name = row.role_name
        this.form.id = row.id
        const res = await distributeUser(row.id)
        // console.log(res)
        this.rolesList = res.data
      }
      this.dialogFormVisible = true
    },
    // 搜索用户
    searchTable() {
      this.initUserList()
    },
    // 删除用户
    del(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await delUser(id)
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.initUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleClose() {
      this.form = {
        username: '',
        password: '',
        email: '',
        mobile: '',
      }
      if (this.type !== 'allot') {
        this.$refs.form.resetFields()
      }
    },
  },
  computed: {
    typeTitle() {
      return mapTitle[this.type]
    },
  },
  created() {
    this.initUserList()
  },
}
</script>

<style lang="less" scoped>
.users {
  .el-card {
    .el-input {
      width: 33%;
      margin-right: 20px;
    }
    .el-table {
      margin-bottom: 15px;
    }
  }
  .allot-roles {
    margin: 20px 0;
  }
}
</style>
